package com.zhangj;

import java.io.*;

/**
 * @ClassName SparseArray
 * @Description
 * @Author zhangjie
 * @Date 2022/1/12 8:34
 * @Version 1.0
 */

public class SparseArray {
    public static void main(String[] args) throws IOException {
        int[][] sparseArray = new int[11][11];

        sparseArray[1][2] = 3;
        sparseArray[2][3] = 3;
        sparseArray[4][5] = 3;
        sparseArray[6][2] = 344;

        int count = 0;
        int maxColumn = 0;  //记录一维数组的最大长度
        for (int i = 0; i < sparseArray.length; i++) {
            int[] a = sparseArray[i];
            for (int j = 0; j < a.length; j++) {
                if (sparseArray[i][j] != 0) {
                    count++;
                }

                if (a.length > maxColumn) {
                    maxColumn = a.length;
                }
            }
        }

        int[][] reducedArray = new int[count + 1][3];

        reducedArray[0][0] = sparseArray.length;
        reducedArray[0][1] = maxColumn;
        reducedArray[0][2] = sparseArray.length * maxColumn;

        int rowStart = 1;
        int columnStart = 0;
        for (int i = 0; i < sparseArray.length; i++) {
            int[] a = sparseArray[i];
            for (int j = 0; j < a.length; j++) {
                if (sparseArray[i][j] != 0) {
                    reducedArray[rowStart][columnStart++] = i;
                    reducedArray[rowStart][columnStart++] = j;
                    reducedArray[rowStart][columnStart++] = sparseArray[i][j];

                    rowStart++;
                }
            }
            columnStart = 0;
        }

        for (int[] a : sparseArray) {
            for (int i : a) {
                System.out.print(i + "\t");
            }
            System.out.println();
        }

        System.out.println("===========================");

        for (int[] a : reducedArray) {
            for (int i : a) {
                System.out.print(i + "\t");
            }
            System.out.println();
        }

        System.out.println("============================");
        int[][] restoredArray = new int[reducedArray[0][0]][reducedArray[0][1]];

        for (int i = 1; i < reducedArray.length; i++) {
            int[] a = reducedArray[i];
            restoredArray[a[0]][a[1]] = a[2];
        }

        for (int[] ints : restoredArray) {
            for (int anInt : ints) {
                System.out.print(anInt+"\t");
            }
            System.out.println();
        }

        FileOutputStream fileOutputStream = new FileOutputStream(new File("array.txt"));

        for (int[] ints : reducedArray) {
            for (int anInt : ints) {
                fileOutputStream.write((anInt + "").getBytes());
            }
        }
    }
}
